const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
const financeData = "d_finance"
var wxContext = {};

exports.main = async (event, context) => {
	wxContext = cloud.getWXContext()

	switch (event.funName) {
		case "getFinance":
			return await getFinance();
		case "addItem":
			return await addItem(event);
		case "save":
			return await save(event);
		case "getList":
			return await getList(event);
		default:
			break;
	}
}
async function _initData() {
	let data = {
		items:[{
			name:"资产",
			items:[{
				name:"流动",
				items: []
			},{
				name:"固定",
				items: []
			}]
		},{
			name:"负债",
			items:[{
				name:"短期",
				items: []
			},{
				name:"长期",
				items: []
			}]
		}],
		t:new Date().getTime(),
		e:true,
		name:'',
		userId:wxContext.OPENID
	}
	await db.collection(financeData)
		.add({
			data: data,
			success(res) {
				console.log(res);
			},
			fail(res) {
				throw res;
			}
		})
}
async function getFinance() {
	let result = await db.collection(financeData)
		.where({
			userId:_.eq(wxContext.OPENID),
			e: _.eq(true)
		})
		.field({
			items: true
		})
		.orderBy('t', 'desc')
		.limit(1)
		.get();
	if (result && result.data) {
		if (result.data.length > 0) {
			return result.data[0];
		} else {
			// 新增
			await _initData();
			return await getFinance();
		}
	}
	return result;
}
async function addItem() {

}
async function save() {

}
async function getList() {

}
